#pragma once
#include <common.h>
#ifdef LIB_LAS
#include <LasOperator.h>
#endif

namespace evaluation{
	
	std::string getFileName(std::string filePath)
	{
		int fileNameLastIdx = filePath.rfind(".");
		std::string tmp = filePath.substr(0, fileNameLastIdx);
		int fileNameFirstIdx = tmp.rfind("/");
		if(fileNameFirstIdx != -1)
			return tmp.substr(fileNameFirstIdx+1, fileNameLastIdx-1);
		else
			return tmp;
	}

	class PointCloudReader
	{
	private:
		std::vector<std::string> file_lists;
		std::string type;
	public:
		std::vector<std::string>& getFileList(){ return file_lists;}
		void readFileList(std::string path)
		{
			struct dirent *ptr;
			DIR *dir;
			dir = opendir( path.c_str() );
			
			while( (ptr=readdir(dir)) != NULL )
			{
				// skip '.' and '..'
				if(ptr->d_name[0] == '.')
					continue;
				
				// skip the files that we are not need 
				
				std::string _filename = ptr->d_name;
				type = _filename.substr(_filename.rfind(".")+1);
				
				if(type != "las" && type != "xyz" && type != "asc" && type != "pcd")
				{
					std::cout << "仅支持点云类型: pcd|las|xyz|asc, 不支持当前类型: " << type << "!" << std::endl;
					exit(-1);
				}

				// get full path
				file_lists.push_back( (path+'/'+ptr->d_name).c_str() );
			}
			
			std::sort(file_lists.begin(), file_lists.end());
		}

		int readCloud(std::string file_path, PointCloud::Ptr cloud)
		{
			cloud->clear();
			#ifdef LIB_LAS
			if(type == "las") return las2pcd(file_path, cloud);
			#endif

			if(type == "pcd") return pcl::io::loadPCDFile<PointType>(file_path.c_str(), *cloud);
			
			if(type == "xyz" || type == "asc" || type == "txt")
			{
				PointType pt;
				std::string s;
				std::ifstream input_file(file_path.c_str());
				while(std::getline(input_file, s)){
					std::istringstream iss(s);
					if(iss>>pt.x && iss>>pt.y && iss>>pt.z)
						cloud->points.emplace_back(std::move(pt));

					if(input_file.eof()) break;
				}
				input_file.close();

				if(cloud->points.size() == 0) {
					std::cout << "No points in file: " << file_path << "!" << std::endl;
					return -1;
				}

				cloud->height = 1;
				cloud->width = cloud->points.size();
				cloud->is_dense = false;
				return 0;
			}
		}
	};
}